//
//  HYRechargeViewController.m
//  HaiYue
//
//  Created by skyline on 2018/6/13.
//  Copyright © 2018年 skyline. All rights reserved.
//

#import "HYRechargeViewController.h"
#import "HYRechargeView.h"
#import <WebKit/WebKit.h>
@interface HYRechargeViewController ()<WKNavigationDelegate>
@property (nonatomic, strong) HYRechargeView *rechargeView;
@property (nonatomic, strong) WKWebView *web;
@end

@implementation HYRechargeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.title = @"平台币";
    
    CCGradientLayer *layer = [CCGradientLayer layerWithColors:@[(__bridge id)THEME_COLOR.CGColor, (__bridge id)[UIColor whiteColor].CGColor] locations:@[@0.3, @0.5, @1.0] startPoint:CGPointMake(0, 0) endPoint:CGPointMake(0, 1.0) frame:self.view.frame];
    [self.view.layer addSublayer:layer];
    [CCNotice addObs:self sel:@selector(actionForHYRechargeView:) name:HYRechargeViewRecharge obj:nil];
    // Do any additional setup after loading the view.
}

- (HYRechargeView *)rechargeView
{
    if (!_rechargeView)
    {
        _rechargeView = [[HYRechargeView alloc] init];
        _rechargeView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_rechargeView];
        [_rechargeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsZero);
        }];
    }
    return _rechargeView;
}
- (WKWebView *)web
{
    if (!_web)
    {
        _web = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _web.scrollView.bounces = NO;
        _web.navigationDelegate = self;
        [self.view addSubview:_web];
        [_web mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsZero);
        }];
    }
    return _web;
}
- (void)show:(NSString *)url
{
    [self clearCookie];
    
    NSString *new_url  = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:new_url]];
    request.HTTPMethod = @"GET";
    request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;//设置缓存的请求策略
    [self.web loadRequest:request];
}

- (void)clearCookie
{
    NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
    NSString *cachesDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *tmpDir = NSTemporaryDirectory();
    NSString *bundleId  =  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    
    NSString *webkitFolderInLib = [NSString stringWithFormat:@"%@/WebKit",libraryDir];
    NSString *webKitFolderInCaches = [NSString stringWithFormat:@"%@/%@/WebKit",cachesDir,bundleId];
    NSString *webKitFolderInCachesfs = [NSString stringWithFormat:@"%@/%@/fsCachedData",cachesDir,bundleId];
    NSString *webKitFolderInTemp = [NSString stringWithFormat:@"%@/%@/WebKit",tmpDir,bundleId];
    
    NSError *error;
    /* iOS8.0 WebView Cache的存放路径 */
    [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCaches error:&error];
    [[NSFileManager defaultManager] removeItemAtPath:webkitFolderInLib error:nil];
    [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInTemp error:nil];
    
    /* iOS7.0 WebView Cache的存放路径 */
    [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCachesfs error:&error];
}
- (void)actionForHYRechargeView:(NSNotification *)notify
{
    int money = [[notify.userInfo valueForKey:@"money"] intValue];
    int tag = [[notify.userInfo valueForKey:@"index"] intValue];
    
    if (money <= 0 || money > 9999)
        [CCAlert showMessage:@"充值金额范围1～9999" hidden:nil];
    else
    {
        NSString *index = [NSString stringWithFormat:@"%d",tag-200];
        [CCHttp post:API_PAY para:@{@"amount":[notify.userInfo valueForKey:@"money"],@"paychannel":index} success:^(id  _Nonnull response) {
            int code = 0;
            code = [[response valueForKey:@"retcode"] intValue];
            if (code == 100)
                [self show:[response valueForKey:@"weburl"]];
        } fail:^(NSError * _Nonnull error) {
            
        }];
        
//        [HYHttps post:API_PAY para:@{@"amount":[notify.userInfo valueForKey:@"money"],@"paychannel":index} complete:^(id response) {
//            int code = 0;
//            code = [[response valueForKey:@"retcode"] intValue];
//            if (code == 100)
//                [self show:[response valueForKey:@"weburl"]];
//        } fail:^(NSDictionary *dict) {
//            
//        }];
    }
}

- (void)actionForRightNaviBar
{
    [self.navigationController pushViewController:[NSClassFromString(@"HYRechargeRecordViewController") new] animated:YES];
}
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [self startHUD];
    NSLog(@"页面开始加载时调用");
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    NSLog(@"当内容开始返回时调用");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [self endHUD];
    NSLog(@"页面加载完成之后调用");
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    [self endHUD];
    NSLog(@"页面加载失败时调用");
}
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"接收到服务器跳转请求之后调用");
}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    [self endHUD];
    NSLog(@" 跳转失败时调用");
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    WKNavigationActionPolicy policy = WKNavigationActionPolicyAllow;
    if ([[navigationAction.request.URL absoluteString] containsString:@"weixin://"] )
    {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]])
        {
            [AppDelegate openAPP:navigationAction.request.URL.absoluteString];
        }
    }
    else if ([[navigationAction.request.URL absoluteString] containsString:@"mqq://"] )
    {
        [AppDelegate openAPP:navigationAction.request.URL.absoluteString];
    }
    decisionHandler(policy);
}
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    {
        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.style = HYViewNaviBarStyleOnlyLeftBtn;
    self.rechargeView.balance = [HYUserManager manager].user.balance;
}

- (void)dealloc
{
    [CCNotice rmObs:self name:HYRechargeViewRecharge obj:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
